package com.lanxiao.cloud.modules.gateway.route.domain.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lanxiao.cloud.common.core.enums.DelFlagEnum;
import com.lanxiao.cloud.common.mybatis.service.impl.BaseServiceImpl;
import com.lanxiao.cloud.common.core.exception.BusinessException;
import com.lanxiao.cloud.modules.gateway.route.domain.event.GatewayRouteChangeEvent;
import com.lanxiao.cloud.modules.gateway.route.domain.event.GatewayRouteChangePublisher;
import com.lanxiao.cloud.modules.gateway.route.domain.model.GatewayRoute;
import com.lanxiao.cloud.modules.gateway.route.domain.service.IGatewayRouteService;
import com.lanxiao.cloud.modules.gateway.route.infrastructure.error.RouteErrorType;
import com.lanxiao.cloud.modules.gateway.route.infrastructure.repository.GatewayRoutesMapper;
import java.util.Objects;
import org.springframework.stereotype.Service;

/**
 * @author ：qiaoliang
 * @date ：2021-08-19
 */
@Service
public class GatewayRouteServiceImpl extends
    BaseServiceImpl<Long, GatewayRoutesMapper, GatewayRoute> implements
    IGatewayRouteService {

  private final GatewayRouteChangePublisher gatewayRouteProducer;

  public GatewayRouteServiceImpl(
      GatewayRouteChangePublisher gatewayRouteProducer) {
    this.gatewayRouteProducer = gatewayRouteProducer;
  }

  @Override
  public void saveRoute(GatewayRoute gatewayRoute) {
    // 新增时校验服务ID是否存在
    this.verificationServiceId(null, gatewayRoute.getServiceId());
    this.save(gatewayRoute);
    this.changeRoute();
  }

  @Override
  public void updateByIdRoute(GatewayRoute gatewayRoute) {
    // 修改时校验服务ID是否唯一，不包含当前路由服务ID
    this.verificationServiceId(gatewayRoute.getId(), gatewayRoute.getServiceId());
    this.updateById(gatewayRoute);
    this.changeRoute();
  }

  @Override
  public void deleteByIdRoute(Long id) {
    final GatewayRoute gatewayRoute = this.getById(id);
    if(Objects.nonNull(gatewayRoute)){
      gatewayRoute.setDelFlag(DelFlagEnum.DELETE);
      this.updateById(gatewayRoute);
      this.changeRoute();
    }
  }

  /**
   *  触发变动事件
   *
   * @author ：qiaoliang

   * @date 2021-09-09 16:55
   */
  private void changeRoute() {
    gatewayRouteProducer.asyncPublish(new GatewayRouteChangeEvent());
  }

  /**
   * 主键不为空则校验非主键信息的服务ID，为空则校验所有服务ID
   *
   * @author ：qiaoliang
   * @param id :  主键ID
   * @param serviceId : 服务ID
   * @date 2021-09-09 16:56
   */
  private void verificationServiceId(Long id, String serviceId){
    LambdaQueryWrapper<GatewayRoute> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(GatewayRoute::getServiceId, serviceId);
    queryWrapper.notLike(Objects.nonNull(id),GatewayRoute::getId, id);
    BusinessException.isNonNull(this.getOne(queryWrapper), RouteErrorType.SERVICE_ID_ERROR);
  }

}
